<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\OriginBox;
use app\airobot\model\Product;
use app\airobot\model\UserModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 超管系统-盒子管理
 * Class Box
 * @package app\airobot\controller
 */
class Box extends Controller
{
    private $table = 'box';
    public $commonLogic;

    /**
     * 盒子列表
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '盒子列表';
        $query = $this->_query($this->table);
        $where = [];
        if (!empty($_GET['user_id'])) {
            $where['from_user_id'] = $_GET['user_id'];
        }
        $query->where($where);
        $query->order('id asc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        $this->commonLogic = new CommonLogic();
        $ImageUrl = CommonLogic::GetImageUrl();
        // 用户
        $userIds = array_column($data, 'from_user_id');
        $userModel = new UserModel();
        $userList = $userModel->queryList([], ['field' => 'id', 'data' => $userIds], [], [], [], "", $field = "*", $order = "");
        $userMap = array_column($userList, null, 'id');

        // 商品
        $productIds = [];
        foreach ($data as $vo) {
            $showProductsList = explode(";", $vo['show_products']);
            foreach ($showProductsList as $showProductsItem) {
                $showProductsItemArr = explode("|", $showProductsItem);
                $productIds[] = $showProductsItemArr[0];
            }
        }
        $productIds = array_unique($productIds);
        $productModel = new Product();
        $productList = $productModel->queryList([], ['field' => 'id', 'data' => $productIds], [], [], [], "", $field = "*", $order = "");
        $productMap = array_column($productList, null, 'id');
        foreach ($data as &$vo) {
            $vo['username'] = isset($userMap[$vo['from_user_id']]) ? $userMap[$vo['from_user_id']]['username'] : '';
            $vo['amount'] = $this->commonLogic->DealAmount($vo['amount']);
            if ($vo['description'] == "") {
                $vo['description'] = $vo['name'];
            }
            if (strlen($vo['description']) > 50) {
                $vo['description'] = $this->commonLogic->TruncateString($vo['description'], 50) . "...";
            }
            if ($vo['from_user_id'] == "0") {
                $vo['from_user_id'] = "系统";
            }
            $vo['image'] = $ImageUrl['box'] . $vo['image'];
            // 展示商品
            $productIdsArr = [];
            $showProductsList = explode(";", $vo['show_products']);
            foreach ($showProductsList as $showProductsItem) {
                $showProductsItemArr = explode("|", $showProductsItem);
                $productIdsArr[] = $showProductsItemArr[0];
            }
            $productTotalAmount = 0;
            $showProductsImage = [];
            foreach ($productIdsArr as $productId) {
                // 金额
                $productAmount = isset($productMap[$productId]) ? $productMap[$productId]['amount'] : '0';
                $productTotalAmount = (float)$productTotalAmount + (float)$productAmount;
                // 图片
                $productImage = isset($productMap[$productId]) ? $ImageUrl['product'] . $productMap[$productId]['image'] : '';
                if ($productImage != "") {
                    $showProductsImage[] = $productImage;
                }
            }
            $vo['product_total_amount'] = $this->commonLogic->DealAmount($productTotalAmount);
            $vo['show_products_image'] = $showProductsImage;
        }
    }

    public function dealDecimal($data)
    {
        foreach ($data as $key => $value) {
            if ($key == "amount") {
                $data[$key] = floatval($value);
            }
        }
        return $data;
    }

    /**
     * 添加数据字典
     * @auth true
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->checkCreateAndEdit(false);
            $createData = [];
            $createData["from_user_id"] = 0;
            $createData["name"] = $data["name"];
            $createData["description"] = $data["description"];
            $createData["image"] = $data["image"];
            $createData["is_hot"] = $data["is_hot"];
            $createData["amount"] = $data["amount"];
            $createData["product_ids"] = $data["product_ids"];
            $createData["show_products"] = $data["show_products"];
            $createData["rtp"] = $data["rtp"];
            $createData["tags"] = $data["tags"];
            $createData["status"] = 1;
            $boxModel = new \app\airobot\model\Box();
            $boxModel->createInfo($createData);
            $this->success("保存成功！");
        } else {
            OriginBox::mForm('form');
        }
    }

    /**
     * 编辑数据字典
     * @auth true
     */
    public function edit()
    {
        $this->commonLogic = new CommonLogic();
        if ($this->request->isPost()) {
            $this->checkCreateAndEdit(true);
            $this->success("保存成功！");
        }

        $boxModel = new \app\airobot\model\Box();
        $vo = $boxModel->queryInfo(["id" => $_GET["id"]]);
        $rtpArr = json_decode($vo["rtp"], true);
        $index = 0;
        foreach ($rtpArr as $k => $rtpItem) {
            $vo["RTP" . (++$index)] = $k . "==" . $rtpItem;
        }
        $vo = $this->dealDecimal($vo);
        $this->vo = $vo;
        OriginBox::mForm('form');
    }

    public function checkCreateAndEdit($isUpdate = true)
    {
        $returnData = [];
        if ($this->request->isPost()) {
            if ($_POST["name"] == "") {
                $this->error("名称错误！");
            }
            if ($_POST["description"] == "") {
                $this->error("描述错误！");
            }
            if ($_POST["tags"] == "") {
                $this->error("标签不能为空！");
            }
            if ($_POST["image"] == "") {
                $this->error("盒子图片错误！");
            }
            if ($_POST["amount"] == "" || $_POST["amount"] < 0) {
                $this->error("开盒金额错误！");
            }
            if ($_POST["show_products"] == "") {
                $this->error("展示商品格式错误！");
            }
            if ($_POST["RTP1"] == "") {
                $this->error("RTP1格式错误！");
            }
            if ($_POST["RTP2"] == "") {
                $this->error("RTP2格式错误！");
            }
            if ($_POST["RTP3"] == "") {
                $this->error("RTP3格式错误！");
            }
            if ($_POST["RTP4"] == "") {
                $this->error("RTP4格式错误！");
            }
            if ($_POST["RTP5"] == "") {
                $this->error("RTP5格式错误！");
            }
            $productModel = new Product();

            // 展示商品校验
            $showProductIds = [];
            $showProductsList = explode(";", $_POST["show_products"]);
            foreach ($showProductsList as $showProductsItem) {
                $showProductsItemArr = explode("|", $showProductsItem);
                if (count($showProductsItemArr) != 3) {
                    $this->error("展示商品格式错误！");
                }
                if ($showProductsItemArr[2] > 1 || $showProductsItemArr[2] < 0) {
                    $this->error("展示商品格式错误！");
                }
                $showProductIds[] = $showProductsItemArr[0];
            }
            sort($showProductIds);
            $productList = $productModel->queryList([], ['field' => 'id', 'data' => $showProductIds], [], [], [], "", $field = "*", $order = "");
            $productMap = array_column($productList, null, 'id');
            $lessThanSpinAmountCount = 0;
            foreach ($showProductIds as $productId) {
                if (!isset($productMap[$productId])) {
                    $this->error("展示商品，未查到信息！");
                }
                if ($productMap[$productId]["amount"] < $_POST["amount"]) {
                    $lessThanSpinAmountCount++;
                }
            }
            if ($lessThanSpinAmountCount == 0) {
                $this->error("没有小于Spin金额的产品！");
            }

            // RTP格式校验
            $rtpProductIdArr = [];
            $dbRtpArr = [];
            foreach ($_POST as $key => $value) {
                if ($key == "RTP1" || $key == "RTP2" || $key == "RTP3" || $key == "RTP4" || $key == "RTP5") {
                    // 解析第一层：用户价值
                    $valueArr = explode("==", $value);
                    if (count($valueArr) != 2) {
                        $this->error($key . ":格式错误！");
                    }
                    $dbRtpArr[$valueArr[0]] = $valueArr[1];

                    // 解析第二层
                    $rtpProductIds = [];
                    $valueList = explode(";", $valueArr[1]);
                    foreach ($valueList as $valueItem) {
                        $valueItemArr = explode("|", $valueItem);
                        if (count($valueItemArr) != 3) {
                            $this->error($key . ":格式错误！");
                        }
                        if ($valueItemArr[2] < 0) {
                            $this->error($key . ":格式错误！");
                        }
                        $rtpProductIds[] = $valueItemArr[0];
                    }
                    sort($rtpProductIds);
                    $rtpProductIdArr[] = $rtpProductIds;
                    $productList = $productModel->queryList([], ['field' => 'id', 'data' => $rtpProductIds], [], [], [], "", $field = "*", $order = "");
                    $productMap = array_column($productList, null, 'id');
                    foreach ($rtpProductIds as $productId) {
                        if (!isset($productMap[$productId])) {
                            $this->error($key . ":未查询到商品信息！");
                        }
                    }
                    unset($_POST[$key]);
                }
            }

            // 各个商品相关配置，ID要一致
            if (count($showProductIds) != count($scrollProductIds)) {
                $this->error("各配置的商品ID，未对齐！");
            }
            foreach ($showProductIds as $key => $productId) {
                if ($scrollProductIds[$key] != $productId) {
                    $this->error("各配置的商品ID，不是一致！");
                }
            }
            foreach ($rtpProductIdArr as $rtpProductIds) {
                if (count($showProductIds) != count($rtpProductIds)) {
                    $this->error("各配置的商品ID，未对齐！");
                }
                foreach ($showProductIds as $key => $productId) {
                    if ($rtpProductIds[$key] != $productId) {
                        $this->error("各配置的商品ID，不是一致！");
                    }
                }
            }

            $productIdsStr = "";
            $showProductIds = array_unique($showProductIds);
            foreach ($showProductIds as $productId) {
                $productIdsStr .= "[" . $productId . "]";
            }
            $_POST['product_ids'] = $productIdsStr;
            $_POST['rtp'] = json_encode($dbRtpArr);
            if ($isUpdate) {
                $boxModel = new \app\airobot\model\Box();
                $boxModel->updateInfo(["id" => $_POST["id"]], $_POST);
            }
            $returnData = $_POST;
        }

        return $returnData;
    }

    /**
     * 查看rtp
     * @auth true
     */
    public function queryrtp()
    {
        $boxModel = new \app\airobot\model\Box();
        $vo = $boxModel->queryInfo(["id" => $_GET["id"]]);
        $rtpArr = json_decode($vo["rtp"], true);
        $index = 0;
        foreach ($rtpArr as $k => $rtpItem) {
            $vo["RTP" . (++$index)] = $k . "==" . $rtpItem;
        }
        $this->vo = $vo;
        OriginBox::mForm('rtp');
    }

    /**
     * 状态
     * @auth true
     */
    public function status()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:1,2,3,4,5' => '状态值范围异常！',
            'status.require' => '状态值错误！',
        ]), 'id');
    }


    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $this->commonLogic = new CommonLogic();
        $list = Db::table('box')->where(['from_user_id' => 0])->select()->toArray();
        foreach ($list as &$vo) {
            // spin金额
            $vo = $this->dealDecimal($vo);
            // rtp
            $rtpArr = json_decode($vo["rtp"], true);
            $index = 0;
            foreach ($rtpArr as $k => $rtpItem) {
                $vo["RTP" . (++$index)] = $k . "==" . $rtpItem;
            }
            // image
            $imageArr = explode("/", $vo['image']);
            $vo['image'] = end($imageArr);
        }


        // 设置 CSV 文件的名字
        $filename = "box.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['id', '名称', '描述', '标签', '图片', '是否热门(0否,1是)', 'spin金额', '展示产品', 'RTP1', 'RTP2', 'RTP3', 'RTP4', 'RTP5', '假滚权重', '假滚序列']);

        // 写入数据行
        foreach ($list as $k => $v) {
            fputcsv($output, [$v['id'], $v['name'], $v['description'], $v['tags'], $v['image'], $v['is_hot'], $v['amount_usd'], $v['show_products'], $v['RTP1'], $v['RTP2'], $v['RTP3'], $v['RTP4'], $v['RTP5'], $v['scroll_product_weight'], $v['scroll_product_serial']]);
        }

        // 关闭输出流
        fclose($output);
    }


    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        $this->_delete($this->table, 'id');
    }
}